<template>
  <section class="todoapp">
    <todo-header @addTask="hAddTask"></todo-header>
    <todo-main @changeAll="hChangeAll" @changeState="hChangeState" @delTask="hDelTask" :list="showList"></todo-main>
    <todo-footer @changeType="hChangeType" @clearDone="hClearDone" :list="showList"></todo-footer>
  </section>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
export default {
  // 注册组件
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('list') || '[]'),
      type: 'all' 
    }
  },
  methods: {
    hDelTask(id) {
      const index = this.list.findIndex(item => item.id === id)
      this.list.splice(index, 1)
    },
    hChangeState(id) {
      const item = this.list.find(item => item.id === id)
      item.isDone = !item.isDone
    },
    hAddTask(taskname) {
      this.list.push({
        id: Date.now(),
        name: taskname,
        isDone: false
      })
    },
    hClearDone() {
      this.list = this.list.filter(item => !item.isDone)
    },
    hChangeType(type) {
      this.type = type
    },
    hChangeAll(val) {
      this.list.forEach(item => item.isDone = val)
    }
  },
  computed: {
    showList() {
      if (this.type === 'yes') {
        return this.list.filter(item => item.isDone)
      } else if (this.type === 'no') {
        return this.list.filter(item => !item.isDone)
      } else {
        return this.list
      }
    }
  },
  watch: {
    list: {
      handler() {
        localStorage.setItem('list', JSON.stringify(this.list))
      },
      deep: true 
    }
  }
}
</script>

<style></style>
